/**
* MediaInfoDLL - All info about mediainfo files, for DLL (JNA version)
*
* Copyright (C) 2009-2009 Jerome Martinez, Zen@MediaArea.net
*
* This library is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
* 参考 net.sourceforge.mediainfo
**/

package com.seeingtv.common.utils.mediainfo;
import static java.util.Collections.singletonMap;

import com.sun.jna.FunctionMapper;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author hubert
 */
public class MediaInfoUtils {
    private static  Logger log = LoggerFactory.getLogger(MediaInfoUtils.class);
   static {
       // libmediainfo for linux depends on libzen
       try {
           // We need to load dependencies first, because we know where our native libs are (e.g. Java Web Start Cache).
           // If we do not, the system will look for dependencies, but only in the library path.
           if (!Platform.isWindows() && !Platform.isMac()) {
               NativeLibrary.getInstance("zen");
           }
       } catch (LinkageError  ex) {
           log.error("Failed to preload libzen",ex);
       }
   }

   /**Internal stuff*/
   interface MediaInfoDLL_Internal extends Library {
       MediaInfoDLL_Internal INSTANCE = (MediaInfoDLL_Internal) Native.loadLibrary((Platform.isWindows()&&Platform.is64Bit())?"mediainfo64":"mediainfo", MediaInfoDLL_Internal.class, singletonMap(OPTION_FUNCTION_MAPPER, (FunctionMapper) (lib, method) -> {
		   // MediaInfo_New(), MediaInfo_Open() ...
		   return "MediaInfo_" + method.getName();
	   }
	   ));


       /**Constructor/Destructor*/
       Pointer New();
       void Delete(Pointer handle);

       /**File*/
       int Open(Pointer handle, WString file);
       void Close(Pointer handle);

       /**Infos*/
       WString Inform(Pointer Handle);
       WString Get(Pointer Handle, int streamKind, int streamNumber, WString parameter, int infoKind, int searchKind);
       WString GetI(Pointer Handle, int streamKind, int streamNumber, int parameterIndex, int infoKind);
       int     Count_Get(Pointer Handle, int streamKind, int streamNumber);

       /**Options*/
       WString Option(Pointer Handle, WString option, WString value);
   }
   private Pointer Handle;

    /**
     *
     */
   public enum StreamKind {
        /**
         * 总体参数
         */
       General,
        /**
         * 视频参数
         */
       Video,
        /**
         * 音频参数
         */
       Audio,
       Text,
       Chapters,
       Image,
       Menu;
   }

   //Enums
   public enum InfoKind {
       /**
        * Unique name of parameter.
        */
       Name,
   
       /**
        * Value of parameter.
        */
       Text,
   
       /**
        * Unique name of measure unit of parameter.
        */
       Measure,
   
       Options,
   
       /**
        * Translated name of parameter.
        */
       Name_Text,
   
       /**
        * Translated name of measure unit.
        */
       Measure_Text,
   
       /**
        * More information about the parameter.
        */
       Info,
   
       /**
        * How this parameter is supported, could be N (No), B (Beta), R (Read only), W
        * (Read/Write).
        */
       HowTo,
   
       /**
        * Domain of this piece of information.
        */
       Domain;
   }

   public MediaInfoUtils() {
       try {
               Handle = MediaInfoDLL_Internal.INSTANCE.New();
       } catch (Throwable ex) {
               if (ex != null){
				   log.error("Error in MediaInfo Library loading: " + ex.getMessage(),ex);
                   if (!Platform.isWindows() && !Platform.isMac()) {
					   log.error("Make sure you have libmediainfo and libzen installed");
                   }
               }
       }
   }
   
   public boolean isValid() {
       return Handle != null;
   }

    public void dispose() {
       if (Handle == null) {
           throw new IllegalStateException();
       }
   
       MediaInfoDLL_Internal.INSTANCE.Delete(Handle);
       Handle = null;
   }

   @Override
   protected void finalize() throws Throwable {
       if (Handle != null) {
           dispose();
       }
   }

   /**
    * Open a file and collect information about it (technical information and tags).
    * 
    * @param filePath full name of the file to open
    * @return 1 if file was opened, 0 if file was not not opened
    */
   public int open(String filePath) {
       return MediaInfoDLL_Internal.INSTANCE.Open(Handle, new WString(filePath));
   }

   /**
    * Close a file opened before with Open().
    * 
    */
   public void close() {
       MediaInfoDLL_Internal.INSTANCE.Close(Handle);
   }

   /**
    * Get all details about a file.
    * 
    * @return All details about a file in one string
    */
   public String inform() {
       return MediaInfoDLL_Internal.INSTANCE.Inform(Handle).toString();
   }

   /**
    * Get a piece of information about a file (parameter is a string).
    * 
    * @param streamKind Kind of Stream (general, video, audio...)
    * @param streamNumber Stream number in Kind of Stream (first, second...)
    * @param parameter Parameter you are looking for in the Stream (Codec, width, bitrate...),
    *            in string format ("Codec", "Width"...)
    * @return a string about information you search, an empty string if there is a problem
    */
   public String get(StreamKind streamKind, int streamNumber, String parameter) {
       return get(streamKind, streamNumber, parameter, InfoKind.Text, InfoKind.Name);
   }


   /**
    * Get a piece of information about a file (parameter is a string).
    * 
    * @param streamKind Kind of Stream (general, video, audio...)
    * @param streamNumber Stream number in Kind of Stream (first, second...)
    * @param parameter Parameter you are looking for in the Stream (Codec, width, bitrate...),
    *            in string format ("Codec", "Width"...)
    * @param infoKind Kind of information you want about the parameter (the text, the measure,
    *            the help...)
    */
   public String get(StreamKind streamKind, int streamNumber,String parameter, InfoKind infoKind) {
       return get(streamKind, streamNumber, parameter, infoKind, InfoKind.Name);
   }


   /**
    * Get a piece of information about a file (parameter is a string).
    * 
    * @param streamKind Kind of Stream (general, video, audio...)
    * @param streamNumber Stream number in Kind of Stream (first, second...)
    * @param parameter Parameter you are looking for in the Stream (Codec, width, bitrate...),
    *            in string format ("Codec", "Width"...)
    * @param infoKind Kind of information you want about the parameter (the text, the measure,
    *            the help...)
    * @param searchKind Where to look for the parameter
    * @return a string about information you search, an empty string if there is a problem
    */
   public String get(StreamKind streamKind, int streamNumber, String parameter, InfoKind infoKind, InfoKind searchKind) {
       return MediaInfoDLL_Internal.INSTANCE.Get(Handle, streamKind.ordinal(), streamNumber, new WString(parameter), infoKind.ordinal(), searchKind.ordinal()).toString();
   }


   /**
    * Get a piece of information about a file (parameter is an integer).
    *
    * @param streamKind Kind of Stream (general, video, audio...)
    * @param streamNumber Stream number in Kind of Stream (first, second...)
    * @param parameterIndex Parameter you are looking for in the Stream (Codec, width, bitrate...),
    *            in integer format (first parameter, second parameter...)
    * @return a string about information you search, an empty string if there is a problem
    */
   public String get(StreamKind streamKind, int streamNumber, int parameterIndex) {
       return get(streamKind, streamNumber, parameterIndex, InfoKind.Text);
   }


   /**
    * Get a piece of information about a file (parameter is an integer).
    *
    * @param streamKind Kind of Stream (general, video, audio...)
    * @param streamNumber Stream number in Kind of Stream (first, second...)
    * @param parameterIndex Parameter you are looking for in the Stream (Codec, width, bitrate...),
    *            in integer format (first parameter, second parameter...)
    * @param infoKind Kind of information you want about the parameter (the text, the measure,
    *            the help...)
    * @return a string about information you search, an empty string if there is a problem
    */
   public String get(StreamKind streamKind, int streamNumber, int parameterIndex, InfoKind infoKind) {
       return MediaInfoDLL_Internal.INSTANCE.GetI(Handle, streamKind.ordinal(), streamNumber, parameterIndex, infoKind.ordinal()).toString();
   }

   /**
    * Count of Streams of a Stream kind (StreamNumber not filled), or count of piece of
    * information in this Stream.
    * @param streamKind Kind of Stream (general, video, audio...)
    * @return number of Streams of the given Stream kind
    */
   public int Count_Get(StreamKind streamKind) {
       return MediaInfoDLL_Internal.INSTANCE.Count_Get(Handle, streamKind.ordinal(), -1);
   }


   /**
    * Count of Streams of a Stream kind (StreamNumber not filled), or count of piece of
    * information in this Stream.
    * @param streamKind Kind of Stream (general, video, audio...)
    * @param streamNumber Stream number in this kind of Stream (first, second...)
    * @return number of Streams of the given Stream kind
    */
   public int Count_Get(StreamKind streamKind, int streamNumber) {
       return MediaInfoDLL_Internal.INSTANCE.Count_Get(Handle, streamKind.ordinal(), streamNumber);
   }

   /**
    * Configure or get information about MediaInfo.
    * @param option The name of option
    * @return Depends on the option: by default "" (nothing) means No, other means Yes
    */
   public String option(String option) {
       return MediaInfoDLL_Internal.INSTANCE.Option(Handle, new WString(option), new WString("")).toString();
   }

   /**
    * Configure or get information about MediaInfo.
    * @param option The name of option
    * @param value The value of option
    * @return Depends on the option: by default "" (nothing) means No, other means Yes
    */
   public String option(String option, String value) {
       return MediaInfoDLL_Internal.INSTANCE.Option(Handle, new WString(option), new WString(value)).toString();
   }

   /**
    * Configure or get information about MediaInfo (Static version).
    * @param option The name of option
    * @return Depends on the option: by default "" (nothing) means No, other means Yes
    */
   public static String optionStatic(String option) {
       return MediaInfoDLL_Internal.INSTANCE.Option(MediaInfoDLL_Internal.INSTANCE.New(), new WString(option), new WString("")).toString();
   }

   /**
    * Configure or get information about MediaInfo(Static version).
    * @param option The name of option
    * @param value The value of option
    * @return Depends on the option: by default "" (nothing) means No, other means Yes
    */
   public static String optionStatic(String option, String value) {
       return MediaInfoDLL_Internal.INSTANCE.Option(MediaInfoDLL_Internal.INSTANCE.New(), new WString(option), new WString(value)).toString();
   }
}
